import random
from lxml import etree
from glob import glob
from .loaders import UniqueGirlLoader, GenericGirlLoader
from .girl_template import GirlTemplate


class GirlManager(object):
	def __init__(self, *args, **kw):
		object.__init__(self)
		self.uniques = []
		self.generics = []
#
#		"actives" are active uniques
#
		self.actives = []

	def scan(self):
		uni_files = glob("resources/characters/*.girlsx")
		gen_files = glob("resources/characters/*.rgirlsx")

		for s in gen_files:
			self.read_generic(s)
			pass

		for s in uni_files:
			self.read_unique(s)

	def read_generic(self, file):
		girl = GirlTemplate()
		tree = etree.parse(file)
		root = tree.getroot()
		loader = GenericGirlLoader()

		for xml_girl in root:
			girl = loader.load(xml_girl)
			self.generics.append(girl)

	def read_unique(self, file):
		tree = etree.parse(file)
		root = tree.getroot()
		loader = UniqueGirlLoader()

		for xml_girl in root:
			girl = loader.load(xml_girl)
			self.uniques.append(girl)

	def random_unique(self, **kw):
		if len(self.uniques) == 0:
			return None
		candidates = self.uniques

		excluded = kw.get("excluding", None)
		needed = kw.get("requiring", None)
		if needed:
			candidates = self.require(candidates, needed)
		if excluded:
			candidates = self.exclude(candidates, excluded)

		if len(candidates) == 0:
			return None
		g = random.choice(candidates)
		self.uniques.remove(g)
		self.actives.append(g)
		g.calc_prices()
		return g

	def random_generic(self, **kw):
		template = random.choice(self.generics)
		g = template.make()
		g.calc_prices()
		return g

	def require(self, candies, needed):
		return [ g for g in candies if g.has_traits(needed) ]

	def exclude(self, candies, needed):
		return [ g for g in candies if g.lacks_traits(needed) ]

girl_manager = GirlManager()
girl_manager.scan()

if __name__ == "__main__":

	for i in range(20):
		break
		g = girl_manager.random_unique(
			requiring=[ "Incorporial" ],
			excluding=[ "Small Boobs" ]
		)
		if g == None:
			print "*** no more matches"
			break
		#print g.name
		g.print_()

	g = girl_manager.random_generic()
	g.print_()
